package htmlparser;

import java.io.IOException;
import java.net.URI;

import org.apache.commons.httpclient.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;

public class HttpClientUtility {

	public static final String RESPONSE_DECODING_CHARSET = "UTF-8";

	public static String getStrByHttp(String url)
			throws ClientProtocolException, IOException {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {

			/*
			 * setProxy(optional)
			 */
			if (LocalProxy.PROXY_USED) {
				HttpHost proxy = new HttpHost(LocalProxy.PROXY_HOST,
						LocalProxy.PROXY_PORT);
				httpclient.getParams().setParameter(
						ConnRoutePNames.DEFAULT_PROXY, proxy);
			}

			/*
			 * request and response
			 */
			HttpGet httpget = new HttpGet(url);

			/* use BasicResponseHandler to get NC response string */

			ResponseHandler<String> responseHandler = new BasicResponseHandler();

			// Logging.logInfo("httpclient request charset: "
			// +
			// httpclient.getParams().getParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET));

			String responseBody = httpclient.execute(httpget, responseHandler);
			responseBody = new String(
					responseBody
							.getBytes(httpclient.getParams().getParameter(
									CoreProtocolPNames.HTTP_CONTENT_CHARSET)
									.toString()), RESPONSE_DECODING_CHARSET);
			return responseBody;
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

	public static void main(String[] args) throws ClientProtocolException, IOException {
		System.out
				.println(getStrByHttp("http://www.google.com.hk/search?hl=zh-CN&safe=strict&q=florist+new+york"));
	}
}
